﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO.Ports;
using System.Threading;

namespace AutoStar.Common
{
    public class LowTemperatureModule
    {
        private SerialPort serialPort;
        private bool isConnected;
        private object lockObject = new object();

        public LowTemperatureModule(string portName, int baudRate = 57600, Parity parity= Parity.None,int dataBits = 8, StopBits stopBits = StopBits.One)
        {
            serialPort = new SerialPort(portName, baudRate, parity, dataBits, stopBits);
            serialPort.NewLine = "\r";
        }

        public bool Connect()
        {
            try
            {
                if (!isConnected)
                {
                    serialPort.Open();
                    isConnected = true;
                    Console.WriteLine("连接成功");
                }
                return isConnected;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"连接失败: {ex.Message}");
                return false;
            }
        }

        public void Disconnect()
        {
            if (isConnected)
            {
                serialPort.Close();
                isConnected = false;
                Console.WriteLine("连接已关闭");
            }
        }

        public string SendCommand(string command)
        {
            //lock (lockObject)
            //{
                if (isConnected)
                {
                    serialPort.WriteLine(command);
                    // 读取响应，假设响应以换行结束
                    return serialPort.ReadLine();
                }
                else
                {
                    Console.WriteLine("连接未建立");
                    return null;
                }
            //}
        }

        public string GetStatus()
        {
            Global.LogHelper.WriteLog("查询实际温度TC1:TCACTTEMP?");
            return SendCommand("TC1:TCACTTEMP?");
        }
    }
}
